<?php
/**
 * Created by PhpStorm.
 * User: 38339
 * Date: 2021-05-21
 * Time: 16:49
 */

namespace app\common\model\auth;
use think\Model;

class CommonAdminAuth extends Model
{
    protected $name = 'common_admin_auth';

    /**
     * @param $models
     * @return array
     */
    public static function fillModels($models)
    {
        $list = [];
        foreach ($models as $model) {
            $listItem = static::fillModel($model);
            $list[] = $listItem;
        }
        return $list;
    }

    public static function fillModel($model)
    {

        $data = [];
        $data['id'] = $model['id'];
        $data['role_id'] = $model['role_id'];
        $data['name'] = $model['name'];
        $data['create_time'] = $model['create_time'];
        $data['menu_ids'] = self::getMenuIdList($model['menu_ids']);
        return $data;
    }

    public static function getMenuIdList($menu_ids){
        if(empty($menu_ids)){
            return [];
        }
        $arr = explode(',',$menu_ids);
        $data = [];
        foreach ($arr as $item){
            $data[] = intval($item);
        }
        return $data;
    }

    /*
     * 获取保存的菜单
     */
    public static function getMenuIds($menuIdArr){
        if(count($menuIdArr) == 0){
            return '';
        }
        $where = [];
        $where[] = ['id','in',$menuIdArr];
        $where[] = ['parent_id','>',0];
        $lists = (new CommonAdminMenu())->field('parent_id')->where($where)->group('parent_id')->select();
        if(count($lists) > 0){
            foreach ($lists as $item){
                $menuIdArr[] = intval($item['parent_id']);
            }
        }
        return implode(',',$menuIdArr);
    }

    /*
     * 获取列表
     */
    public static function getList($where,$limit_start,$page_size){
        $lists = self::alias('a')->join('common_admin_role r','a.role_id = r.id')->field('a.*,r.name')
            ->where($where)->order('a.id','desc')->limit($limit_start,$page_size)->select();
        return self::fillModels($lists);
    }

    /*
     * 获取总数据条数
     */
    public static function getCount($where){
        return self::alias('a')->join('common_admin_role r','a.role_id = r.id')->where($where)->count();
    }

    /*
     * 获取单条数据
     */
    public static function getOne($where){
        return self::where($where)->find();
    }

}